import 'dart:math';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_barrage/flutter_barrage.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/article/comment.dart';
import 'package:ride_rex/main/discover/discover_bean.dart';
import 'package:ride_rex/main/main_logic.dart';
import 'package:ride_rex/main/video/quicker_scrollPhysics.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ride_rex/ui/common_home_scaffold.dart';
import 'package:video_player/video_player.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import '../../generated/assets.dart';
import '../../person_detail/person_detail_logic.dart';
import 'video_logic.dart';

class VideoPage extends StatefulWidget {
  const VideoPage(this.logic, {Key? key}) : super(key: key);

  final VideoLogic logic;

  @override
  State<VideoPage> createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    widget.logic.initData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return const _VideoPage();
  }

  @override
  bool get wantKeepAlive => true;
}

class _VideoPage extends StatefulWidget {
  const _VideoPage();

  @override
  State<_VideoPage> createState() => _ChildVideoPageState();
}

class _ChildVideoPageState extends CommonLifeState<_VideoPage> {
  double bottom = 0;

  late final VideoLogic controller;
  @override
  void initState() {
    super.initState();
    controller = Get.put(VideoLogic());
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();

    setState(() {
      bottom = MediaQueryData.fromWindow(window).viewInsets.bottom;
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<VideoLogic>(
      builder: (logic) {
        return BaseScaffold(
          hideBackBtn: true,
          resizeToAvoidBottomInset: false,
          child: Stack(
            alignment: Alignment.bottomCenter,
            children: [
              Container(
                decoration: CommonDecoration.getShapeDecoration(
                  radius: 0,
                  borderWidth: 0,
                  borderColor: Colors.transparent,
                  gradient: AppColors.primaryGradient,
                ),
                child: Stack(
                  children: [
                    Column(
                      children: [
                        _buildAppBar().padding(top: ScreenUtil().statusBarHeight - 5.w),
                        CommonMargin.height(15.w),
                        PageView.builder(
                          physics: const QuickerScrollPhysics(),
                          controller: logic.pageController,
                          scrollDirection: Axis.vertical,
                          itemCount: logic.list.length,
                          itemBuilder: (context, i) {
                            FeedUserBean bean = logic.list[i];
                            return _VideoItem(
                              bean: bean,
                              onTapComment: (bean) => logic.onTapComment(bean),
                              key: logic.keyList[i],
                            );
                          },
                        ).expanded(),
                      ],
                    ),
                  ],
                ),
              ),
              _buildInput().positioned(
                left: 0,
                right: 0,
                bottom: bottom - (ScreenUtil().bottomBarHeight * 0.5 + CommonHomeScaffold.itemsHeight),
              ),
            ],
          ),
        );
      },
    );
  }

  ///评论输入框
  Widget _buildInput() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w),
      height: 50.w,
      color: const Color(0xfff0f0f0),
      alignment: Alignment.centerLeft,
      child: TextField(
        decoration: InputDecoration(
          hintText: 'Enter your ideas...',
          hintStyle: const TextStyle(fontSize: 15, color: Color(0xFFDDDDDD)),
          fillColor: Colors.white,
          filled: true,
          contentPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 9.w),
          isCollapsed: true,
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(6.w),
            borderSide: BorderSide.none,
          ),
        ),
        style: const TextStyle(fontSize: 15, color: Color(0xFF333333)),
        focusNode: controller.focusNode,
        controller: controller.textEditingController,
        keyboardType: TextInputType.text,
        maxLines: 1,
        minLines: 1,
        textInputAction: TextInputAction.send,
        onEditingComplete: () => controller.sendTextComment(),
      ),
    );
  }

  Widget _buildAppBar() => IconWidget.image(Assets.pngVideoTitle, width: 189.w, height: 43.w);

  @override
  String getRouteName() => Get.currentRoute;
}

class _VideoItem extends StatefulWidget {
  const _VideoItem({required this.bean, this.onTapComment, super.key});

  final FeedUserBean bean;
  final ValueChanged<FeedUserBean>? onTapComment;

  @override
  State<_VideoItem> createState() => VideoItemState();
}

class VideoItemState extends State<_VideoItem> {
  late final VideoPlayerController controller;

  bool isPlaying = true;

  @override
  void initState() {
    super.initState();
    controller = VideoPlayerController.networkUrl(Uri.parse(widget.bean.localVideo ?? ''))
      ..setLooping(true)
      ..addListener(() {
        setState(() {
          isPlaying = controller.value.isPlaying;
        });
      })
      ..initialize().then((_) async {
        if (Get.find<MainLogic>().curPage == 1) {
          ///当前选中的是视频Tab
          playOrPauseVideo();
        }
      });
  }

  /// 判断播放和暂停
  void playOrPauseVideo() {
    if (controller.value.isPlaying) {
      CommonOperate.hideKeyboard();
      controller.pause();
    } else {
      controller.play();
    }
  }

  void play() {
    if (!controller.value.isPlaying) controller.play();
  }

  void pause() {
    if (controller.value.isPlaying) controller.pause();
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  final barrageWallController = BarrageWallController();

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        FractionallySizedBox(widthFactor: 1, child: _buildCover()),
        Center(
          child: FractionallySizedBox(
            widthFactor: 1,
            child: AspectRatio(
              aspectRatio: controller.value.aspectRatio,
              child: _buildVideo(),
            ),
          ),
        ),
        if (widget.bean.videoCommentList.isNotEmpty)
          Positioned(
            top: 50.w,
            width: ScreenUtil().screenWidth,
            height: 100.w,
            child: BarrageWall(
              massiveMode: false,
              bullets: widget.bean.videoCommentList
                  .map((e) => BulletUtils.getBullets(e, widget.bean.videoCommentList.indexOf(e)))
                  .toList(),
              controller: barrageWallController,
              safeBottomHeight: 20,
              speed: 6,
              child: Container(),
            ),
          ),
        _buildMore().positioned(right: 16.w, top: 16.w),
        if (!isPlaying) _buildPlayBtn().center(),
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.transparent,
                Colors.black.withOpacity(0.5),
              ],
            ),
          ),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildTitle(),
              Row(
                children: [
                  Stack(
                    alignment: Alignment.bottomRight,
                    children: [_buildAvatar(), if (widget.bean.isFriend == false) _buildAdd()],
                  ),
                  _buildName().paddingLeft(10.w).expanded(),
                  _buildCommentBtn().paddingRight(20.w),
                  _buildPraiseBtn(),
                ],
              ).paddingBottom(22.w).paddingTop(16.w),
            ],
          ).paddingHorizontal(16.w),
        ).positioned(bottom: 0, left: 0, right: 0),
      ],
    );
  }

  Widget _buildPlayBtn() {
    return Container(
      decoration: CommonDecoration.getShapeDecoration(
        bg: Colors.black.withOpacity(0.5),
        radius: 60.w,
      ),
      alignment: Alignment.center,
      width: 60.w,
      height: 60.w,
      child: ButtonWidget.icon(
        IconWidget.icon(
          Icons.play_arrow,
          size: 40.w,
          color: Colors.white,
        ),
        hasInkWell: false,
        onTap: playOrPauseVideo,
      ),
    );
  }

  ///封面图片
  Widget _buildCover() {
    return ImageWidget.asset('assets/png/${widget.bean.localVideoCover}', fit: BoxFit.fitWidth);
  }

  ///视频
  Widget _buildVideo() => ButtonWidget(
        onTap: playOrPauseVideo,
        hasInkWell: false,
        child: VideoPlayer(controller),
      );

  ///More
  Widget _buildMore() => ButtonWidget.icon(
        IconWidget.image(
          Assets.pngDiscoverMore,
          size: 28.w,
        ),
        hasInkWell: false,
        onTap: () => CommonLogic.onTapMore(widget.bean.userId ?? '', showFollow: widget.bean.isFriend == false),
      );

  ///标题
  Widget _buildTitle() {
    return TextWidget.moreLine(text: widget.bean.videoTitle, fontSize: 16, color: Colors.white);
  }

  ///头像
  Widget _buildAvatar() => ButtonWidget(
        // onTap: () => CommonRoute.open(PersonDetailPage(widget.bean)),
        onTap: () => null,
        hasInkWell: false,
        child: ImageWidget.url(
          widget.bean.avatar ?? '',
          width: 42.w,
          height: 42.w,
          radius: 42.w,
          fit: BoxFit.cover,
        ),
      );

  ///关注
  Widget _buildAdd() => ButtonWidget.icon(
        IconWidget.image(
          Assets.pngDiscoverAdd,
          size: 16.w,
        ),
        hasInkWell: false,
        onTap: () async {
          if (widget.bean.userId.empty) return;
          Loading.show();
          await CommonLogic.follow(widget.bean.userId!);
          Loading.toast('Follow success', closeLoading: true);
        },
      );

  ///昵称
  Widget _buildName() {
    return TextWidget.oneLine(text: widget.bean.nickname, fontSize: 16, color: Colors.white);
  }

  ///评论
  Widget _buildCommentBtn() => ButtonWidget.icon(
        IconWidget.image(
          Assets.pngVideoComment,
          size: 34.w,
        ),
        hasInkWell: false,
        onTap: () => widget.onTapComment?.call(widget.bean),
      );

  ///点赞
  Widget _buildPraiseBtn() {
    bool isLike = widget.bean.isVideoLike;
    return ButtonWidget.icon(
      IconWidget.image(
        isLike ? Assets.pngDiscoverPraiseSelect : Assets.pngDiscoverPraiseNormal,
        size: 34.w,
      ),
      hasInkWell: false,
      onTap: () {
        if (widget.bean.localVideo.empty) return;
        if (isLike) {
          CommonLogic.cancelLike(recordId: widget.bean.localVideo ?? '');
        } else {
          CommonLogic.like(recordId: widget.bean.localVideo ?? '');
        }
      },
    );
  }
}

class BulletUtils {
  static Bullet getBullets(CommentBean e, int index) {
    final showTime = Random().nextInt(6000);
    return Bullet(
      child: Container(
        padding: EdgeInsets.fromLTRB(4.w, 4.w, 12.w, 4.w),
        decoration: CommonDecoration.getShapeDecoration(
          radius: 90.w,
          gradient: LinearGradient(
            begin: Alignment.centerLeft,
            end: Alignment.centerRight,
            stops: const [0, 1],
            colors: [Colors.black.withOpacity(0.6), Colors.black.withOpacity(0)],
          ),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            ImageWidget.url(e.senderAvatar ?? '', width: 32.w, height: 32.w, radius: 32.w),
            CommonMargin.width(8.w),
            TextWidget.oneLine(text: e.text, fontSize: 15, color: Colors.white),
          ],
        ),
      ),
      showTime: index * 2000,
    );
  }
}
